package cn.edu.gxnu;
import cn.edu.gxnu.TcpServer.ClientHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

/**
 * 简单的回显处理程序实现。
 */
public class EchoHandler implements ClientHandler {
    /**
     * 处理客户端连接，实现回显逻辑。
     */
    @Override
    public void handle(Socket clientSocket, TcpServer.Logger logger) throws IOException {
        String clientInfo = clientSocket.getInetAddress() + ":" + clientSocket.getPort();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(
                     clientSocket.getOutputStream(), true)) {

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                logger.log("收到来自 " + clientInfo + " 的数据: " + inputLine);
                String response = "ECHO: " + inputLine;
                out.println(response);
            }

            // 客户端正常断开连接
            logger.log("客户端断开连接: " + clientInfo);
        } catch (SocketException e) {
            // 客户端异常断开连接
            logger.log("客户端异常断开: " + clientInfo + " - " + e.getMessage());
            throw e;
        }
    }
}